package com.fingard.crypto;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class TripleDES {

	/**
     * 3DES加密，DESede/CBC/PKCS5Padding
     * @param p_key 24位密钥
     * @param p_iv 8位向量
     * @param p_plainData 明文字节
     * @return 密文字节
     * @throws Exception
     */
	public static byte[] encryptCBC(byte[] p_key, byte[] p_iv, byte[] p_plainData) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(p_key);
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("DESede");
        deskey = keyFac.generateSecret(spec);
 
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        IvParameterSpec ivps = new IvParameterSpec(p_iv);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ivps);
        byte[] cipherBytes = cipher.doFinal(p_plainData);
        return cipherBytes;
    }
 
	/**
     * 3DES解密，DESede/CBC/PKCS5Padding
     * @param p_key 24位密钥
     * @param p_iv 8位向量
     * @param p_cipherData 密文字节
     * @return 明文字节
     * @throws Exception
     */
    public static byte[] decryptCBC(byte[] p_key, byte[] p_iv, byte[] p_cipherData) throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(p_key);
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("DESede");
        deskey = keyFac.generateSecret(spec);
 
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        IvParameterSpec ivps = new IvParameterSpec(p_iv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ivps);
 
        byte[] plainBytes = cipher.doFinal(p_cipherData);
        return plainBytes;
    }
}
